package com.im;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

// 客户端
class Client extends Thread {
    private ObjectInputStream mReceiver;    // 数据接收者
    private ObjectOutputStream mSender;     // 数据发送者
    private final Server mServer;           // 服务器
    private final Socket mSocket;           // 客户端套接字

    /**
     * 构造方法。
     * @param server    服务器
     * @param socket    客户端套接字
     */
    public Client(Server server, Socket socket) {
        try {
            mReceiver = new ObjectInputStream(socket.getInputStream());
            mSender = new ObjectOutputStream(socket.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }

        mServer = server;
        mSocket = socket;
    }

    /**
     * 接收数据的线程方法。
     */
    @Override
    public void run() {
        while (mSocket.isConnected()) {
            try {
                // 接收数据并转换成协议
                final ImProtocol pro = (ImProtocol)mReceiver.readObject();
                
                // 处理协议
                mServer.onGetMessageFromClient(pro, this);
            } catch (Exception e) {
                break;
            }
        }

        try {
            if (mReceiver != null) {
                mReceiver.close();
            }
            if (mSender != null) {
                mSender.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送数据。
     * @param pro   协议
     */
    public void sendData(ImProtocol pro) {
        if (mSocket.isClosed()) {
            return;
        }
        
        try {
            mSender.writeObject(pro);
            
            // 防止发送过快导致客户端无法响应
            Thread.sleep(100);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
